<template>
  <div class="main-main">
    <div class="top-main">
      <el-card class="cardAccount">
        <div>
          <el-avatar
          src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
          />
        </div>
        <el-descriptions column="1" class="accountDescription">
          <el-descriptions-item label="用户名：">{{ account.username }}</el-descriptions-item>
          <el-descriptions-item label="电话：">{{ account.phone }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ account.address }}</el-descriptions-item>
          <el-descriptions-item label="余额">{{ account.money }}
            <el-button v-if="admin === '2'" 
            type="primary" 
            plain 
            style="margin-left: 20px;" 
            @click="recharge"
            >
            充值
            </el-button>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-table :data="books" border header-align="center" align="center" class="recommendList">
        <el-table-column fixed prop="bookId" label="书号" width="100" ></el-table-column>
        <el-table-column fixed prop="bookName" label="书名" width="300"></el-table-column>
        <el-table-column fixed prop="author" label="作者" width="200" ></el-table-column>
        <el-table-column fixed label="操作" width="200">
          <template v-slot="{row}">
            <el-button @click="checkBook(row)" plain type="info">详情</el-button>
            <el-button plain @click="borrowMsg(row)">借阅</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-divider class="divider-main"/>
    <div class="bottom-main">
      <el-container>
          <el-main class="picture">
            <apexchart type="bar" :options="chartOptions1" :series="chartData1" class="leftChart"/>
            <apexchart type="line" :options="chartOptions2" :series="chartData2" class="rightChart"/>
          </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios, { AxiosError } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import VueApexCharts from 'vue3-apexcharts'
export default {
    name: 'Main',
    data(){
      return {
        account:{
          username:'',
          phone:'',
          address:'',
          money: '',

        },
        books: [],
        dialogVisible : ref(false),
        username:localStorage.getItem('username'),
        admin: localStorage.getItem('admin'),
      }
    },
    methods:{
      checkBook(row){
        this.$router.push({name: 'BookInfo' , query:{bookId:row.bookId}})
      },

      //使用结构赋值进行异常处理
			promise_error_process(promise){
				return promise.then(data=>[null,data])
								.catch(err=>[err,null])
			},

      recharge(){
        ElMessageBox.prompt('请输入充值金额', '充值', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
      })
        .then(({ value }) => {
          ElMessage({
            type: 'success',
            message: `成功充值${value}元`,
          })
          this.rechargeMoney(this.account.username , this.account.money)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '充值失败',
          })
          })
      },

      //获取推荐图书列表
      async getRecommendByAjax(){
        const response = await axios({
          url:      `http://127.0.0.1:8080/api/books/recommend`,
          method:   'GET',
          withCredentials:  true
        })
        return response
      },
      async getRecommend(){
        const [err , result] = await this.promise_error_process(this.getRecommendByAjax())
        if(err){
          console.log("请求失败")
        }
        else{
          console.log(result)
          this.books = result.data.data
        }
      },

      //借阅图书
      async borrowBookByAjax(bookId){
        const response = await axios({
          url:      `http://127.0.0.1:8080/api/borrow/${this.username}/${bookId}`,
          method:   'GET',
          withCredentials:  true
        })
        return response
      },
      async borrowMsg(row){
        console.log(row.bookId)
        const [err,result] = await this.promise_error_process(this.borrowBookByAjax(row.bookId))
        if(err){
          console.log(err)
        }
        else{
          console.log(result)
          ElMessageBox.confirm('借阅已成功，您可以到我的借阅中查看借阅的详细信息', '借阅成功', {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'success' // 设置对话框类型为成功
        }).then(() => {
          ElMessage({
            type: 'success',
            message: '借阅成功'
          });
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '借阅成功'
          });
        });
        }
      },

      //获取用户信息
      async getAccountByAjax(){
        const response = await axios({
					url				: `http://127.0.0.1:8080/api/users/${this.username}`,
					method			: 'GET',
					withCredentials : true
				})
				return response
      },
      async getAccount(){
        const [err,result] = await this.promise_error_process(this.getAccountByAjax())
        if(err){
          console.log(err)
        }
        else{
          console.log(result)
          this.account.username = result.data.data.username
          this.account.address = result.data.data.address
          this.account.phone = result.data.data.phone
          this.account.money = result.data.data.money
          console.log(this.account)
        }
      },

      //线下充值
      async rechargeByAjax(username , money){
        const response = await axios({
          url:      `http://127.0.0.1:8080/api/users/addMoney/${username}/${money}`,
          method:   'POST',
          withCredentials: true,

        })
        return response
      },
      async rechargeMoney(username , money){
        const [err , result] = await this.promise_error_process(this.rechargeByAjax(username , money))
        if(err){
          console.log("请求失败")
        }
        else{
          this.account.money = result.data.data.money
          console.log("充值成功")
        }
          
      },
    },
    created() {
      this.$store.commit('minusState')
      this.getRecommend()
      this.getAccount()
    },
    components: {
    apexchart: VueApexCharts,
  },
  setup() {
    const chartData1 = ref([{
      name: 'Series 1',
      data: [30, 40, 50, 49, 60 , 125]
    }]);

    const chartOptions1 = ref({
      chart: {
        type: 'bar',
      },
      xaxis: {
        categories: ['计算机', '历史', '文学', '科幻', '小说', '外语'],
      },
    });


    const chartData2 = ref([{
      name: 'Series 1',
      data: [30, 40, 45, 50, 49, 60, 70, 91, 125 , 120 , 50 , 78]
    }]);

    const chartOptions2 = ref({
      chart: {
        type: 'line',
      },
      xaxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep' , 'Oct' , 'Nov' , 'Dec'],
      },
    });

    return {
      chartData1,
      chartOptions1,
      chartData2,
      chartOptions2,
    };
  },
}
</script>

<style scoped>
  .main-main{
    overflow-y: auto;
    position: absolute; /* 设置 test 为绝对定位 */
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  .top-main{
    display: flex;
  }
  .cardAccount{
    height: 200px;
    width: 400px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .bottom-main{
    height: 50%;
  }
  .recommend{
    width: 50%;
    height: 200px;
  }
  .picture{
    width: 50%;
    display: flex;
  }
  .recommendList{
    margin-left: 450px;
    margin-right: 50px;
    height: 200px;
    width: 820px;
    overflow: hidden;
    position: absolute;
  }
  .divider-main{
    width: 90%;
    margin-left: 5%;
    border-style: dashed;
    border-color: #ccc;
    
  }
  .leftChart{
    width: 500px;
    height: 400px;
  }
  .rightChart{
    width: 500px;
    height: 400px;
    margin-left: 50px;
  }
</style>